﻿/*
 * @autor: hectorea
 * @date: 31/07/12
 * @project: LonguestPalindrome
 * 
 */
namespace LonguestPalindrome
{
    /// <summary>
    /// Get the longuest palindrome within a string
    /// </summary>
    internal static class StringExtension
    {
        /// <summary>
        /// Find the longuest palindrome in a string (if exists)
        /// </summary>
        /// <param name="input">Input string</param>
        /// <returns>The longuest palindrome in a string</returns>
        internal static string LonguestPalindrome(this string input)
        {
            string palindrome = string.Empty;
            string word = string.Empty;

            int i = 0;
            while (i < input.Length)
            {
                word += input[i];

                int j = i + 1;
                while (j < input.Length)
                {
                    word += input[j];

                    if (IsPalindrome(word))
                    {
                        if (word.Trim().Length > palindrome.Trim().Length)
                        {
                            palindrome = word;
                        }
                    }

                    j++;
                }

                i++;

                word = string.Empty;
            }


            return palindrome;
        }

        /// <summary>
        /// Verify if a string is palidrome or not
        /// </summary>
        /// <param name="input">Input string</param>
        /// <returns>True if the string is palindrome; false in another case</returns>
        internal static bool IsPalindrome(this string input)
        {
            if (input == string.Empty || input.Length <= 1)
                return false;

            int i = 0, j = input.Length - 1;
            while (i < j)
            {
                while (i < input.Length && input[i] == ' ')
                    i++;
                while (j >= 0 && input[j] == ' ')
                    j--;

                if (i >= input.Length || j < 0 || input[i] != input[j])
                    return false;

                i++;
                j--;
            }

            return true;
        }
    }
}
